package sve.generator;

import java.io.PrintStream;
import java.util.ArrayList;

import cmdp.HierarchicalParser;
import xadd.XADD;

public class Generator {

	public static void generateDBN() {
		print(System.out, generateB(2).toString());
		print(System.out, generateO().toString());
	}

	private static Variable generateO() {
		// Variable o; // = new IntDecVar("");
		// Variable v = new IntDecVar("x1<2");
		// v.setTrue(StringVar.getInstance("-.2*x1"));
		// v.setFalse(DoubleVar.zero);
		// v = new IntDecVar("x1>0", v, DoubleVar.zero);
		// o = new BoolDecVar("b1", v, DoubleVar.zero);
		// // o.setTrue(v);
		// v = new IntDecVar("x1>2");
		// v.setTrue(StringVar.getInstance("-.2*x1"));
		// v.setFalse(DoubleVar.zero);
		// v = new IntDecVar("x1<3", v, DoubleVar.zero);
		// o.setFalse(v);

		return new BoolDecVar("b2", build("!b{i}&x{i}>0&x{i}<2&x2>0&0.5", 5), build("!b1&x1>2&x1<4&x2>0&0.75*x1-1.3"));

	}

	private static Variable getVariable(String s) {
		if (s.startsWith("!")) {
			return new BoolDecVar(s.substring(1));
		}

		return new IntDecVar(s);
	}

	private static Variable build(String expr, int count) {
		Variable v = null, parent = null, prev = null;
		for (int i = 1; i <= count; i++) {
			v = build(expr.replace("{i}", Integer.toString(i)));
			if (parent == null) {
				parent = v;
			} else {
				prev.getTrue().setTrue(v);
				prev.setFalse(DoubleVar.zero);
			}
			prev = v.getTrue();
		}

		return parent;
	}

	private static Variable build(String expr) {
		String[] s = expr.split("&"); // it is the AND sign
		Variable init = getVariable(s[0]), prev = init;
		for (int i = 1; i < s.length - 1; i++) {
			Variable v = getVariable(s[i]);
			prev.setTrue(v);
			prev.setFalse(new DoubleVar("0"));
			prev = v;
		}
		prev.setTrue(new StringVar(s[s.length - 1]));
		prev.setFalse(new DoubleVar("0"));

		return init;
	}

	private static Variable generateB(int count) {
		if (count < 1)
			return null;

		Variable b1 = new BoolDecVar("b1");
		b1.setTrue(new DoubleVar("1"));
		b1.setFalse(new DoubleVar(".1"));

		Variable prevB = b1;
		for (int i = 1; i < count; i++) {
			Variable b = new BoolDecVar("b" + (i + 1));
			b.setTrue(prevB);
			b.setFalse(new DoubleVar(".1"));
			prevB = b;
		}
		return prevB;
	}

	private static void print(PrintStream ps, String str) {
		ps.println(str);
	}
}
